#include <Starflub/string.h>

inline int SFCharToUpperCase(int ch) {
	if ( (unsigned int)(ch - 'a') < 26u )
		ch += 'A' - 'a';
	return ch;
}

int SFCStringGetLength(SFCString c_str) {
	int i;
	while(c_str[i++]);
	return --i;
}

void SFCStringConcatenate(SFCString s1, SFCString s2) {
	int len1 = SFCStringGetLength(s1);
	int totallen = len1+SFCStringGetLength(s2);
	int i;
	SFCString olds1 = s1;
	s1 = '\0';
	for(i = 0; i < totallen; i++)
		*s1++ = s2[i];
}

void strreverse(char* begin, char* end) {
	char aux;
	while(end>begin)
		aux=*end, *end--=*begin, *begin++=aux;
}

div_t div(int val1, int val2) {
	div_t retn;
	retn.quot = val1/val2;
	retn.rem = val1%val2;
	return retn;
}
	
void itoa(int value, char* str, int base) {
	static char num[] = "0123456789abcdefghijklmnopqrstuvwxyz";
	char* wstr=str;
	int sign;
	div_t res;
	
	// Validate base
	if (base<2 || base>35){ *wstr='\0'; return; }
	
	// Take care of sign
	if ((sign=value) < 0) value = -value;
	
	// Conversion. Number is reversed.
	do {
		res = div(value,base);
		*wstr++ = num[res.rem];
	} while(value=res.quot);
	
	if(sign<0) *wstr++='-';	
	*wstr='\0';

	// Reverse string	
	strreverse(str,wstr-1);
}


SFCString SFCStringFromInt(int value) {
	char *c;
	itoa(value, c, 10);
	return c;
}
/*
extern void *memset(void *dest, char val, size_t count)
{
    char *temp = (char *)dest;
    for( ; count != 0; count--) *temp++ = val;
    return dest;
}
*/
